package charlie.shop.filters;

import com.charlie.beans.Users;
import com.charlie.db.DAOLocal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Base for filters
 *
 * @author Kobzev Misha <kobzevmisha@gmail.com>
 */
public class AbstractFilter implements Filter {

    protected ArrayList<String> rolesList;
    @EJB
    protected DAOLocal dao;

    /**
     * Get all roles
     *
     * @param config filter config
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig config) throws ServletException {
        String urls = config.getInitParameter("roles");
        try {
            StringTokenizer token = new StringTokenizer(urls, ",");

            rolesList = new ArrayList<String>();

            while (token.hasMoreTokens()) {
                rolesList.add(token.nextToken());
            }
        } catch (Exception ex) {
            Logger.getLogger(AdminFilter.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * filter url by user role
     *
     * @param req
     * @param res
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = (HttpSession) request.getSession(true);
        List<String> PRolesList = null;
        try {
            //get roles
            if (session.getAttribute("UserRoles") == null) {
                Users user = (Users) session.getAttribute("user");
                if (user == null) {
                    session.setAttribute("PageToRedirect", request.getRequestURI());
                    response.sendRedirect("/CharlieShop-war/signin");
                    return;
                }
                PRolesList = dao.getUserPersonalRolesByEmail(user.getEmail());
                PRolesList.addAll(dao.getUserGroupRolesByEmail(user.getEmail()));
                session.setAttribute("UserRoles", PRolesList);
            } else {
                PRolesList = (List<String>) session.getAttribute("UserRoles");
            }
            //compare with roles from web.xml
            boolean enoughRights = false;
            if ((rolesList == null) || (PRolesList == null)) {
                session.setAttribute("PageToRedirect", request.getRequestURI());
                response.sendRedirect("/CharlieShop-war/signin");
                return;
            }
            for (String s : PRolesList) {
                for (String r : rolesList) {
                    if (r.equals(s.trim())) {
                        enoughRights = true;
                        break;
                    }
                }
            }

            if (!enoughRights) {
                session.setAttribute("PageToRedirect", request.getRequestURI());
                response.sendRedirect("/CharlieShop-war/signin");
                return;
            }
            chain.doFilter(req, res);
        } catch (Exception ex) {
            Logger.getLogger(AdminFilter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * release resources
     */
    @Override
    public void destroy() {
        rolesList.clear();
    }
}
